package com.medicine.service.impl;

import com.medicine.dao.inter.CombatScoreDao;
import com.medicine.exception.BusinessException;
import com.medicine.model.CombatScores;
import com.medicine.service.ICombatScoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 输赢分数记录操作类
 * Created by Guyver.com on 2017/10/27 13:24.
 */
@Service
public class CombatScoreServiceImpl implements ICombatScoreService {
    private Logger logger = LoggerFactory.getLogger(CombatScoreServiceImpl.class);
    @Autowired
    private CombatScoreDao combatScoreDao;

    private void checkPrimaryKey(String id) throws BusinessException {
        if(id==null || "".equals(id)) {
            throw new BusinessException("id：用户id，不允许为空，请检查！");
        }
    }

    public CombatScores getPlayerCombatScores(String id) throws Exception {
        try {
            checkPrimaryKey(id);
            return this.combatScoreDao.selectByPrimaryKey(id);
        }catch (Exception e) {
            logger.error("查询记分板出错，原因：", e);
            throw e;
        }
    }

    public void addPlayerCombatScores(String id) throws Exception {
        try {
            checkPrimaryKey(id);
            CombatScores combatScores = new CombatScores();
            combatScores.setId(id);
            this.combatScoreDao.insert(combatScores);
        }catch (Exception e) {
            logger.error("新增记分板出错，原因：", e);
            throw e;
        }
    }

    public void updatePlayerCombatScores(String id, String code) throws Exception {
        try {
            checkPrimaryKey(id);
            if(code==null || "".equals(code)) {
                throw new BusinessException("code 不允许为空，请检查！");
            }
            CombatScores retCombatScores = this.getPlayerCombatScores(id);
            if(retCombatScores == null) {
                this.addPlayerCombatScores(id);
            }
            CombatScores combatScores = new CombatScores();
            combatScores.setId(id);
            switch (code) {
                case "0" : combatScores.setWin(1); break;
                case "1" : combatScores.setLoss(1); break;
                case "2" : combatScores.setDraw(1); break;
                default: throw new BusinessException("注意：code传值范围为 【0：赢，1：输，2：平。】 请重试！");
            }
            this.combatScoreDao.updateByPrimaryKey(combatScores);
        }catch (Exception e) {
            logger.error("更新记分板出错，原因：", e);
            throw e;
        }
    }
}
